import NProgress from 'nprogress'
import router from './router'
import store from './store'

// 定义白名单 不受权限控制的页面
const whiteList = ['/login', '/404']

// 路由前置守卫
// eslint-disable-next-line space-before-function-paren
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  // 判断有无token
  if (store.getters.token) {
    // 如果有 token 继续判断是否去登录页
    if (to.path === '/login') {
      next('/') // 跳转到主页
    } else {
      if (!store.state.user.userInfo.id) {
        const { roles } = await store.dispatch('user/getUserProfile')
        const routes = await store.dispatch('permission/filterRoutes', roles.role_menus)
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }]) // 添加动态路由到路由表
        await store.dispatch('article/getCates')
        await store.dispatch('article/getTags')
        next(to.path) // 放行通过
      } else {
        next() // 放行通过
      }
    }
  } else { // 无 token
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})
